package com.changgou.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.content.feign.ContentFeign;
import com.changgou.content.pojo.Content;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

/**
 * @Author: wzw
 * @Date: 2020/12/13 0:45
 * @version: 1.8
 */
@CanalEventListener
public class CanalDataEventListenerContent {

    //注入远程调用Feign对象
    @Autowired
    private ContentFeign contentFeign;

    //注入Redis对象
    @Autowired
    private StringRedisTemplate  stringRedisTemplate;

    //自定义监听器(服务器名,数据库名,表名,事件类型(插入,修改))
    @ListenPoint(destination = "example",schema = "changgou_content",table = {"tb_content"},eventType = {CanalEntry.EventType.INSERT, CanalEntry.EventType.UPDATE})
    public void onEventContent(CanalEntry.EntryType entryType,CanalEntry.RowData rowData){
         //获取分类id(行对象,行名)
        String categoryId =getColumnValue(rowData,"category_id");
        //通过分类id查询广告列表
        List<Content> list = contentFeign.findContentListByCategoryId(Long.parseLong(categoryId));
        //存入Redis中
        stringRedisTemplate.boundValueOps("content_"+categoryId).set(JSON.toJSONString(list));
    }

    /**
     * @author wzw
     * 获取该行在数据库中的category_id
     * @Date 15:12 2020/12/13
     * @param rowData 修改行的内容
     * @param columnName 行名(key)
     * @return java.lang.String categoryId
    **/
    private String getColumnValue(CanalEntry.RowData rowData, String columnName) {
        //获取行内对象
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        //循环对象
        for (CanalEntry.Column column : afterColumnsList) {
            //比较key 行名
            if (columnName.equals(column.getName())){
                //返回value 行值
                return column.getValue();
            }
        }
        return null;
    }

}
